package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.GoodsConverter;
import com.cskaoyan.wordmemorize.dao.entity.GoodsDO;
import com.cskaoyan.wordmemorize.dao.mapper.GoodsMapper;
import com.cskaoyan.wordmemorize.dto.admin.DeleteGoodsOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.GoodsDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.AppGoodsDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.GoodsCommand;
import com.cskaoyan.wordmemorize.request.GoodsPageRequest;
import com.cskaoyan.wordmemorize.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsConverter goodsConverter;

    /**
     * 分页获取商品信息(后台商品管理)
     * @param request 分页请求对象，包含分页参数和关键词等信息
     * @return 包含商品信息的分页数据
     */
    @Override
    public PageDTO<GoodsDTO> getGoodsPage(GoodsPageRequest request) {
        LambdaQueryWrapper<GoodsDO> wrapper = new LambdaQueryWrapper<>();
        // 只查未逻辑删除的
        wrapper.eq(GoodsDO::getIsDeleted, 0);
        // 如果请求中包含关键词，则添加模糊查询条件
        if (request.getKeyword() != null && !request.getKeyword().isEmpty()) {
            wrapper.like(GoodsDO::getName, request.getKeyword());
        }
        // 如果是后台也只显示上架商品，取消注释
        // wrapper.eq(GoodsDO::getStatus, 1);

        // 创建分页对象，指定当前页码和每页数量
        Page<GoodsDO> page = new Page<>(request.getPageNum(), request.getCount());
        // 分页查询
        Page<GoodsDO> result = goodsMapper.selectPage(page, wrapper);
        return goodsConverter.goodsPage2PageDTO(result.getRecords(), result.getTotal());
    }

    /**
     * 添加商品
     * @param command 商品的相关信息
     */
    @Override
    @OperateLog(dataType = "商品", operateType = 1, description = "新增商品")
    public void addGoods(GoodsCommand command) {
        // 商品价格校验
        if (command.getPrice() == null  ||
                command.getPrice().compareTo(java.math.BigDecimal.ZERO) < 0 ||
                command.getPrice().compareTo(new java.math.BigDecimal("1000000")) > 0) {

            throw new BusinessException(ResultCodeEnum.PAY_PRICE_ERROR);
        }
        // 商品价格数据类型校验
        if (command.getPrice().scale() > 2) {
            throw new BusinessException(ResultCodeEnum.PAY_PRICE_ERROR);
        }

        GoodsDO goodsDO = goodsConverter.command2GoodsDO(command);
        // 设置商品为未删除状态
        goodsDO.setIsDeleted(0);

        goodsMapper.insert(goodsDO);
    }

    /**
     * 更新商品
     * @param command  商品的更新信息
     */
    @Override
    @OperateLog(dataType = "商品", operateType = 4, description = "修改商品")
    public void updateGoods(GoodsCommand command) {
        // 商品价格校验
        if (command.getPrice() == null  ||
                command.getPrice().compareTo(java.math.BigDecimal.ZERO) < 0 ||
                command.getPrice().compareTo(new java.math.BigDecimal("1000000")) > 0) {

            throw new BusinessException(ResultCodeEnum.PAY_PRICE_ERROR);
        }
        GoodsDO goodsDO = goodsConverter.command2GoodsDO(command);
        goodsMapper.updateById(goodsDO);
    }

    /**
     * 删除商品
     * @param goodsId
     * @return
     */
    @Override
    @OperateLog(dataType = "商品", operateType = 2, description = "删除商品", logReturnValue = true)
    public DeleteGoodsOperateDTO deleteGoods(Long goodsId) {
        GoodsDO goodsDO = goodsMapper.selectById(goodsId);
        if (goodsDO == null){
            throw new BusinessException(ResultCodeEnum.GOODS_NOT_EXIST);
        }

        // 设置商品为已删除状态
        goodsDO.setIsDeleted(1);
        // 根据商品主键更新数据库中的商品删除状态
//        goodsMapper.updateById(goodsDO);
        goodsMapper.deleteById(goodsDO);
        return goodsConverter.goodsDO2DeleteGoodsDTO(goodsDO);
    }

    /**
     * 批量删除商品
     * @param command 包含要删除的商品 ID 列表
     * @return
     */
    @Override
    @OperateLog(dataType = "商品", operateType = 3, description = "批量删除商品", logReturnValue = true)
    public List<DeleteGoodsOperateDTO> deleteGoodsSelected(BatchDeleteCommand command) {
        List<DeleteGoodsOperateDTO> result = new ArrayList<>();
        for (String idStr : command.getIds()) {
            Long id = Long.parseLong(idStr);
            // 调用删除商品方法删除单个商品
            DeleteGoodsOperateDTO dto = deleteGoods(id);
            if (dto != null)
                result.add(dto);
        }
        return result;
    }

    /**
     * 更新商品状态
     * @param goodsId 要更新状态的商品的 ID
     * @param status 新的状态值
     */
    @Override
    @OperateLog(dataType = "商品", operateType = 5, description = "修改商品状态")
    public void updateGoodsStatus(Long goodsId, Integer status) {
        GoodsDO goodsDO = goodsMapper.selectById(goodsId);
        if (goodsDO != null) {
            goodsDO.setStatus(status);
            goodsMapper.updateById(goodsDO);
        }
    }

    /**
     * App端获取商品列表
     * @param request 分页请求对象，包含分页参数和商品类型等信息
     * @return 包含商品信息的分页数据
     */
    @Override
    public PageDTO<AppGoodsDTO> getAppGoodsPage(GoodsPageRequest request) {
        LambdaQueryWrapper<GoodsDO> wrapper = new LambdaQueryWrapper<>();
        // 只查未逻辑删除的
        wrapper.eq(GoodsDO::getIsDeleted, 0);
        // 只查上架的商品
        wrapper.eq(GoodsDO::getStatus, 1);

        // 如果请求中包含商品类型，则添加类型查询条件
        if (request.getTypes() != null && !request.getTypes().isEmpty()) {
            wrapper.in(GoodsDO::getType, request.getTypes());
        }

        // 判断是否有关键词，有关键词则添加模糊查询条件
        if (request.getKeyword() != null && !request.getKeyword().trim().isEmpty()) {
            wrapper.like(GoodsDO::getName, request.getKeyword().trim());
        }

        // 判断是否有分页参数，有则分页查询，没有则全查询
        if (request.getPageNum() != null && request.getCount() != null) {
            // 创建分页对象，指定当前页码和每页数量
            Page<GoodsDO> page = new Page<>(request.getPageNum(), request.getCount());
            // 分页查询
            Page<GoodsDO> result = goodsMapper.selectPage(page, wrapper);
            return goodsConverter.goodsPage2AppPageDTO(result.getRecords(), result.getTotal());
        } else {
            // 没有分页参数，查询全部
            List<GoodsDO> goodsList = goodsMapper.selectList(wrapper);
            return goodsConverter.goodsPage2AppPageDTO(goodsList, (long) goodsList.size());
        }
    }
}
